package com.unitd.frame.sso.common.token;

import com.unitd.frame.comm.bean.BaseBean;
import com.unitd.frame.sso.common.config.SSOConfig;
import com.unitd.frame.comm.utils.RandomUtil;
import com.unitd.frame.sso.exception.SsoException;

/**
 * @desc APP 授权 Token
 * @filename ApiToken.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/10/14
 */
@SuppressWarnings("serial")
public class ApiToken extends BaseBean {

	private String token; 								// 一次性票据
	private String accessToken; 						// 访问票据
	private String aesKey; 								// AES密钥
	private String data; 								// 预留字段,用于存储token的其他信息

	protected ApiToken() {
	}

	public ApiToken(String token, String accessToken) {
		this.token = token;
		this.accessToken = generateAccessToken(accessToken);
		this.aesKey = RandomUtil.getCharacterAndNumber(43);
	}

	/**
	 * @desc 生成访问票据
	 * @param accessToken 访问票据
	 * @return 访问票据
	 */
	private String generateAccessToken(String accessToken) {
		try {
			SSOConfig config = SSOConfig.getInstance();
			return config.getEncrypt().encrypt(accessToken, config.getSecretkey());
		} catch (Exception e) {
			throw new SsoException(e);
		}
	}

	/**
	 * @desc 解密访问票据
	 * @param accessToken 访问票据
	 * @return 解密后的访问票据
	 */
	public static String decryptAccessToken(String accessToken) {
		try {
			SSOConfig config = SSOConfig.getInstance();
			return config.getEncrypt().decrypt(accessToken, config.getSecretkey());
		} catch (Exception e) {
			throw new SsoException(e);
		}
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getAesKey() {
		return aesKey;
	}

	public void setAesKey(String aesKey) {
		this.aesKey = aesKey;
	}
	
	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}
}